<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {router} from "../../router/index.js";
import CreateProduct from "./CreateProduct.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import ModifyInventory from "./ModifyInventory.vue";

const search=ref({})

const currentPage=ref(1)
const pageSize=ref(2)
const total=ref(0)
const handleSizeChange=(val)=>{
  pageSize.value=val
  getProductList()
}
const handleCurrentChange = (val)=>{
  currentPage.value=val
  getProductList()
}
const tableData=ref([])
const getProductList=()=>{
  axios.post(`/carcenter-service-order/products/list/${currentPage.value}/${pageSize.value}`, search.value)
      .then(resp => {
        console.log('接口返回:', resp); // 调试
        const data = resp.data?.data?.data;
        tableData.value = Array.isArray(data) ? data : [];
        total.value = resp.data?.data?.total || 0;
      })
      .catch(err => {
        console.error('请求失败:', err);
        tableData.value = [];
        total.value = 0;
      });
}
const handleSearch =()=>{
  getProductList();
}
const handleAdd =()=>{
  router.push({name:'CreateProduct'})
}

const getStockDialogVisible = (val)=>{
  stockVisible.value=val
}
const handleDelete = (row)=>{
  ElMessageBox.confirm(
      '<strong>确定要删除这条商品数据吗？</strong><br><span style="color: red;">删除后无法恢复</span><br><span style="color: gray;">请问还要继续吗？</span>',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
  )
      .then(() => {
        axios.delete(`/carcenter-service-order/products/delete/${row.id}`).then(resp=>{
          ElMessage.success(resp.data)
          getProductList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
}
const stockVisible=ref(false)
const currentStock=ref(0)
const id=ref()
const modify =(row)=>{
  axios.get(`/carcenter-service-order/products/getProduct/${row.id}`).then(resp=>{
    currentStock.value=resp.data.data.inventory
  })
  stockVisible.value=true
  id.value=row.id
}
const matchCarModel =(row)=>{
  router.push({name:'CarModel',query: { id : row.id }})
}
const discontinued = (row)=>{
  axios.put(`/carcenter-service-order/products/put/discontinued/${row.id}`).then(resp=>{
    ElMessage.success(resp.data)
    getProductList();
  })
}
const handleEdit = (row)=>{
  router.push({name:'UpdateProduct',query: { id : row.id }})
}
const handleUpdateStock = ({id,newStock})=>{
  const item = tableData.value.find(item=>item.id===id)
  if (item){
    item.inventory=newStock
  }

}
onMounted(()=>{
  getProductList();
})

</script>

<template>
  <div class="product-management">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="search.productName" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="生命周期">
        <el-select v-model="search.lifecycle" placeholder="不限" style="width: 200px">
          <el-option label="在售" value="在售"></el-option>
          <el-option label="停售" value="停售"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-button type="danger" @click="handleAdd">新增</el-button>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="productName" label="商品名称"></el-table-column>
      <el-table-column prop="inventory" label="库存"></el-table-column>
      <el-table-column prop="unitName" label="单位"></el-table-column>
      <el-table-column prop="brandName" label="品牌"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="standardPrice" label="标准价"></el-table-column>
      <el-table-column prop="retailPrice" label="零售价"></el-table-column>
      <el-table-column prop="costPrice" label="成本价"></el-table-column>
      <el-table-column prop="lifecycle" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.lifecycle==='在售'" type="success">在售</el-tag>
          <el-tag v-else type="danger">停售</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="productDescription" label="商品介绍"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)" style="color:red;">删除</el-button>
          <el-button size="mini" type="text" @click="modify(scope.row)">修改库存</el-button>
          <el-button size="mini" type="text" @click="matchCarModel(scope.row)">匹配车型</el-button>
          <el-button v-if="scope.row.lifecycle !== '停售'" size="mini" type="text" @click="discontinued(scope.row)">停售</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <div style="text-align: center; padding: 20px;">
          <i class="iconfont icon-zanwushangpin" style="font-size: 80px"></i>
          <p>暂无数据</p>
        </div>
      </template>
    </el-table>

  </div>

  <!-- 分页组件 -->
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[4, 10, 20, 40]"
      :size="'small'"
      :disabled="false"
      :background="false"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="text-align: center; margin-top: 20px;"
  >

  </el-pagination>

<ModifyInventory :stockVisible="stockVisible" :currentStock="currentStock" :id="id" @stockDialogVisible="getStockDialogVisible" @update-stock="handleUpdateStock"></ModifyInventory>
</template>

<style scoped>

</style>